//
//  SearchViewController.m
//  HelpThePoor
//
//  Created by van7ish on 2016/12/4.
//  Copyright © 2016年 van7ish. All rights reserved.
//

#import "SearchViewController.h"
#import "BookTableViewCell.h"
#import "magazineTableViewCell.h"
#import "VideoTableViewCell.h"
#import "BookDetailViewController.h"
#import "MagazineDetailViewController.h"

@interface SearchViewController () <UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource>

/** 导航条 */
@property (nonatomic, strong) UIImageView * navBar;
/** 搜索框 */
@property (nonatomic, strong) UISearchBar * searchBar;
/** 返回按钮 */
@property (nonatomic, strong) UIButton * cancelButton;
/** 搜索按钮 */
@property (nonatomic,strong) UIButton * searchButton;
/** 历史记录列表 */
@property (nonatomic, strong) UITableView * historyTableView;
/** 历史记录搜索内容 */
@property (nonatomic, strong) NSMutableArray * keyWordArr;
/** 历史记录头视图 */
@property (nonatomic, strong) UIView * historyHeaderView;
/** 搜索结果列表 */
@property (nonatomic, strong) UITableView * resultTableView;
/** 搜索结果数据源 */
@property (nonatomic, strong) NSMutableArray * resultArr;
/** 搜索结果头视图 */
@property (nonatomic, strong) UIView * resultHeaderView;
/** 搜索类别选择 */
@property (nonatomic, strong) UIButton * optionButton;
/** 搜索类别视图 */
@property (nonatomic, strong) UIView * optionView;


@end

@implementation SearchViewController

- (NSMutableArray *)resultArr{
    if (!_resultArr) {
        _resultArr = [[NSMutableArray alloc] init];
    }
    return _resultArr;
}

- (NSMutableArray *)keyWordArr{
    if (!_keyWordArr) {
        _keyWordArr = [NSMutableArray array];
        NSData *searchKeyWordsData = [[NSUserDefaults standardUserDefaults] objectForKey:@"searchKeyWords"];
        [_keyWordArr addObjectsFromArray:[NSKeyedUnarchiver unarchiveObjectWithData:searchKeyWordsData]];
    }
    return _keyWordArr;
}

- (UIView *)optionView{
    if (!_optionView) {
        _optionView = [[UIView alloc] initWithFrame:CGRectMake(SCREEN_W - 130 , 55, 70, 120)];
        _optionView.backgroundColor = [UIColor colorWithRed:70 / 255.0 green:180 / 255.0 blue:78 / 255.0 alpha:1];
        _optionView.layer.cornerRadius = 6;
        _optionView.alpha = 0.8;
        NSArray *arr = @[@"书籍", @"期刊", @"视频"];
        for (int i = 0; i < arr.count; i ++) {
            UIButton *tagButton = [[UIButton alloc] initWithFrame:CGRectMake(0, i % arr.count * 40, _optionView.frame.size.width, _optionView.frame.size.height / arr.count)];
            [tagButton setTitle:arr[i] forState:UIControlStateNormal];
            [tagButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
            tagButton.titleLabel.font = FONTSIZE(16);
            [_optionView addSubview:tagButton];
            
            if (i == 0) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, tagButton.frame.size.height - 1, tagButton.frame.size.width - 40, 1)];
                line.backgroundColor = COLOR_WHITE;
                [tagButton addSubview:line];
            } else if (i == 1) {
                UIView *line = [[UIView alloc] initWithFrame:CGRectMake(20, tagButton.frame.size.height - 1, tagButton.frame.size.width - 40, 1)];
                line.backgroundColor = COLOR_WHITE;
                [tagButton addSubview:line];
            } else {
                
            }
            
            __weak typeof(self)weakSelf = self;
            [tagButton initWithBlock:^(UIButton *button) {
                DLog(@"%@", button.titleLabel.text);
                [weakSelf.optionButton setTitle:button.titleLabel.text forState:UIControlStateNormal];
                [weakSelf.optionView removeFromSuperview];
                weakSelf.optionButton.selected = NO;
                
            } for:UIControlEventTouchUpInside];
            
            
        }
    }
    return _optionView;
}

- (UIButton *)optionButton{
    if (!_optionButton) {
        _optionButton = [[UIButton alloc] initWithFrame:CGRectMake(self.searchBar.frame.size.width - 70, 0, 60, self.searchBar.frame.size.height)];
        [_optionButton setTitle:@"书籍" forState:UIControlStateNormal];
        [_optionButton setTitleColor:COLOR_WHITE forState:UIControlStateNormal];
        _optionButton.titleEdgeInsets = UIEdgeInsetsMake(0, - 10, 0, 10);
        [_optionButton setImage:ImageNamed(@"baisanjiao") forState:UIControlStateNormal];
        _optionButton.imageEdgeInsets = UIEdgeInsetsMake(0, 33, 0, - 33);
        _optionButton.titleLabel.font = FONTSIZE(15);
        __weak typeof(self)weakSelf = self;
        [_optionButton initWithBlock:^(UIButton * optionButton) {
            DLog(@"选择搜索分类");
            optionButton.selected = !optionButton.selected;
            if (optionButton.selected) {
                [weakSelf.view addSubview:weakSelf.optionView];
            } else {
                [weakSelf.optionView removeFromSuperview];
            }
            
        } for:UIControlEventTouchUpInside];
        
    }
    return _optionButton;
}

- (UIView *)resultHeaderView{
    if (!_resultHeaderView) {
        _resultHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W, HeightScale(44))];
        _resultHeaderView.backgroundColor = COLOR_LIGHTBGCOLOR;
        
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(WidthScale(15), 0, WidthScale(200), _resultHeaderView.frame.size.height)];
//        label.text = @"共52条记录";
        label.tag = 10;
        label.font = FONTSIZE(17);
        label.textColor = COLOR_GREEN;
        [_resultHeaderView addSubview:label];
        _resultHeaderView.hidden = YES;
    }
    return _resultHeaderView;
}

- (UITableView *)resultTableView{
    if (!_resultTableView) {
        _resultTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + HeightScale(44), SCREEN_W, SCREEN_H - 64 - HeightScale(44)) style:UITableViewStylePlain];
        _resultTableView.delegate = self;
        _resultTableView.dataSource = self;
        _resultTableView.tableFooterView = [UIView new];
        _resultTableView.backgroundColor = COLOR_DEEPBGCOLOR;
        _resultTableView.hidden = YES;
    }
    return _resultTableView;
}

- (UIView *)historyHeaderView{
    if (!_historyHeaderView) {
        _historyHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_W, HeightScale(50))];
        _historyHeaderView.backgroundColor = COLOR_DEEPBGCOLOR;
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(WidthScale(15), HeightScale(17.5), 80, 15)];
        imageView.image = ImageNamed(@"lishijilu");
        
        
        UIButton *clearButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - 52, HeightScale(3), WidthScale(44), HeightScale(44))];
        [clearButton setTitle:@"清空" forState:UIControlStateNormal];
        clearButton.titleLabel.font = FONTSIZE(16);
        [clearButton setTitleColor:COLOR_FONTBLACK forState:UIControlStateNormal];
        __weak typeof(self)weakSelf = self;
        [clearButton initWithBlock:^(id obj) {
            DLog(@"清空历史记录");
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"searchKeyWords"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            [weakSelf.keyWordArr removeAllObjects];
            
            [weakSelf.historyTableView reloadData];
            
        } for:UIControlEventTouchUpInside];
        [_historyHeaderView addSubview:imageView];
        [_historyHeaderView addSubview:clearButton];
        
    }
    return _historyHeaderView;
}

- (UITableView *)historyTableView{
    if (!_historyTableView) {
        _historyTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64 + HeightScale(50), SCREEN_W, SCREEN_H - 64 - HeightScale(50)) style:UITableViewStylePlain];
        _historyTableView.delegate = self;
        _historyTableView.dataSource = self;
        _historyTableView.tableFooterView = [UIView new];
        _historyTableView.backgroundColor = COLOR_DEEPBGCOLOR;
    }
    return _historyTableView;
}

/*
 返回按钮
 */
- (UIButton *)cancelButton{
    if (!_cancelButton) {
        _cancelButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 20, 44, 44)];
        [_cancelButton setTitle:@"返回" forState:UIControlStateNormal];
        _cancelButton.titleLabel.font = FONTSIZE(17);
        __weak typeof(self)weakSelf = self;
        [_cancelButton initWithBlock:^(id obj) {
            DLog(@"返回");
            [weakSelf.optionView removeFromSuperview];
            weakSelf.optionButton.selected = NO;
            if (weakSelf.resultTableView.hidden) {
                [weakSelf dismissViewControllerAnimated:NO completion:nil];
            } else {
                weakSelf.resultTableView.hidden = weakSelf.resultHeaderView.hidden = YES;
            }
            
        } for:UIControlEventTouchUpInside];
    }
    return _cancelButton;
}
/*
 搜索按钮
 */
- (UIButton *)searchButton{
    if(!_searchButton){
        _searchButton = [[UIButton alloc] initWithFrame:CGRectMake(SCREEN_W - 50, 20, 44, 44)];
        [_searchButton setTitle:@"搜索" forState:UIControlStateNormal];
        _searchButton.titleLabel.font = FONTSIZE(17);
        [_searchButton addTarget:self action:@selector(searchListener) forControlEvents:UIControlEventTouchUpInside];
    }
    return _searchButton;
}

/**
 搜索按钮的点击事件
 */
-(void)searchListener{
    DLog(@"searchListener");
    // 搜索功能
    [self requestSearch];
    // 添加搜索历史
    [self addHistory];
}
/**
 搜索结果添加历史记录
 */

- (void) addHistory{

    //将搜索内容添加到历史记录里
    [self.keyWordArr  insertObject: self.searchBar.text atIndex:0];
    //数组去重
    NSMutableArray *listArray = [[NSMutableArray alloc]init];
    for (NSString *str in self.keyWordArr) {
        if (![listArray containsObject:str]) {
            [listArray addObject:str];
        }
    }
    [self.keyWordArr removeAllObjects];
    [self.keyWordArr addObjectsFromArray:listArray];
    
    [self.historyTableView reloadData];
    
    NSData *searchKeyWordsData = [NSKeyedArchiver archivedDataWithRootObject:self.keyWordArr];
    
    [[NSUserDefaults standardUserDefaults] setObject:searchKeyWordsData forKey:@"searchKeyWords"];

}
- (UISearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(55, 22, SCREEN_W - 108, 40)];
        _searchBar.delegate = self;
        _searchBar.placeholder = @"输入感兴趣的内容";
        _searchBar.backgroundImage = [UIImage new];
        _searchBar.tintColor = COLOR_GREEN;
        [_searchBar becomeFirstResponder];
    
        UITextField *searchTextField=[_searchBar valueForKey:@"_searchField"];
        searchTextField.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
        searchTextField.layer.cornerRadius = 4.0;
        searchTextField.textColor=[UIColor whiteColor];
        [searchTextField setValue:[UIColor whiteColor]forKeyPath:@"_placeholderLabel.textColor"];
        searchTextField.clearButtonMode = UITextFieldViewModeNever;
        
        [_searchBar addSubview:self.optionButton];
    }
    return _searchBar;
}

- (UIImageView *)navBar{
    if (!_navBar) {
        _navBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 64)];
        _navBar.image = ImageNamed(@"daohangtiao");
        _navBar.userInteractionEnabled = YES;
    }
    return _navBar;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = COLOR_LIGHTBGCOLOR;
    
    [self.navBar addSubview:self.searchBar];
    
    [self.navBar addSubview:self.cancelButton];
    
    [self.navBar addSubview:self.searchButton];
    
    [self.view addSubview:self.navBar];
    
    [self.view addSubview:self.historyTableView];
    
    [self.view addSubview:self.historyHeaderView];
    
    [self.view addSubview:self.resultTableView];
    
    [self.view addSubview:self.resultHeaderView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)dealloc{
    DLog(@"%s", __func__);
}

#pragma mark - UITableViewDelegate & UITableViewDataSource Methods

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([tableView isEqual:self.historyTableView]) {
        return self.keyWordArr.count;
    } else {
        return self.resultArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.historyTableView]) {
        static NSString *cellID = @"historyCell";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
        if (!cell) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            cell.imageView.image = ImageNamed(@"search_2");
            cell.backgroundColor = COLOR_LIGHTBGCOLOR;
            cell.textLabel.font = FONTSIZE(17);
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            [cell setSeparatorInset:UIEdgeInsetsMake(0, 12, 0, 12)];
        }
        cell.textLabel.text = self.keyWordArr[indexPath.row];
        return cell;
    } else {
        //搜索结果
        if ([self.optionButton.titleLabel.text isEqualToString:@"书籍"]) {
            static NSString *cellID = @"bookCell";
            BookTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[BookTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            
            cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.resultArr[indexPath.row][@"name"]];
            cell.descLabel.text = [NSString stringWithFormat:@"%@", self.resultArr[indexPath.row][@"summaryText"]];
            cell.authorLabel.text = [NSString stringWithFormat:@"%@", [self.resultArr[indexPath.row][@"author"] length] ? self.resultArr[indexPath.row][@"author"] : @"连环画"];
            
            NSString *coverImageFile = [NSString stringWithFormat:@"%@%@", KHostAddress, self.resultArr[indexPath.row][@"coverImageFile"]];
            [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverImageFile] placeholderImage:ImageNamed(@"placeholdershuji")];
            return cell;
        } else if ([self.optionButton.titleLabel.text isEqualToString:@"期刊"]) {
            static NSString *cellID = @"magazineCell";
            MagazineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[MagazineTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            
            cell.titleLabel.text = [NSString stringWithFormat:@"%@", self.resultArr[indexPath.row][@"name"]];
            cell.descLabel.text = self.resultArr[indexPath.row][@"summarytext"];

            cell.timeLabel.text = self.resultArr[indexPath.row][@"publishTime"];
            
            NSString *coverimgpath = [NSString stringWithFormat:@"%@%@", KHostAddress, self.resultArr[indexPath.row][@"coverimgpath"]];
            [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:coverimgpath] placeholderImage:ImageNamed(@"placeholdershuji")];

            return cell;
        } else {
            //视频
            static NSString *cellID = @"videoCell";
            VideoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
            if (!cell) {
                cell = [[VideoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
            }
            
            [cell.coverImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@", KHostAddress, self.resultArr[indexPath.row][@"coverImageFile"]]] placeholderImage:ImageNamed(@"placeholdershipin")];
            cell.titleLabel.text = self.resultArr[indexPath.row][@"name"];
            cell.descLabel.text = self.resultArr[indexPath.row][@"summarytext"];
            cell.authorLabel.text = self.resultArr[indexPath.row][@"author"];
            cell.timeLabel.text = [Tool dateConvert:self.resultArr[indexPath.row][@"publishTime"]];
            
            return cell;
        }
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([tableView isEqual:self.historyTableView]) {
        return HeightScale(48);
    } else if ([self.optionButton.titleLabel.text isEqualToString:@"视频"]) {
        return HeightScale(145);
    } else {
        return SCREEN_W / 2.6;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    DLog(@"index = %ld", indexPath.row);
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if ([tableView isEqual:self.historyTableView]) {
        self.resultTableView.hidden = self.resultHeaderView.hidden = NO;
        self.searchBar.text = cell.textLabel.text;
        [self.searchBar resignFirstResponder];
        [self.optionView removeFromSuperview];
        self.optionButton.selected = NO;
        
        [self requestSearch];
    } else {
        DLog(@"push");

        if (self.delegate) {
            [self dismissViewControllerAnimated:NO completion:^{
                NSInteger type;
                if ([self.optionButton.titleLabel.text isEqualToString:@"书籍"]) {
                    type = 1;
                } else if ([self.optionButton.titleLabel.text isEqualToString:@"期刊"]) {
                    type = 4;
                } else {
                    type = 2;
                }
                [self.delegate resultDetail:type dataDic:self.resultArr[indexPath.row]];
            }];
            
        }
    
    }
}

#pragma mark - UIScrollViewDelegate Method

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    [self.searchBar resignFirstResponder];
}

#pragma mark - UISearchBarDelegate Methods

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    DLog(@"搜索");
    [self requestSearch];
    //添加搜索历史记录
    [self addHistory];
    
}

#pragma mark - data request

- (void)requestSearch{
    //键盘消失
    [self.searchBar resignFirstResponder];
    
    NSString *URL = [NSString string];
    if ([self.optionButton.titleLabel.text isEqualToString:@"书籍"]) {
        URL = [NSString stringWithFormat:KgetBookByClick, KHostAddress, KOrganizationID, @(1), @"", @"", @(1)];
        URL = [URL stringByAppendingFormat:@"&keyWord=%@", self.searchBar.text];
    } else if ([self.optionButton.titleLabel.text isEqualToString:@"期刊"]) {
        URL = [NSString stringWithFormat:KgetMagazineByClick, KHostAddress, KOrganizationID, @(1), @"", @(1)];
        URL = [URL stringByAppendingFormat:@"&keyWord=%@", self.searchBar.text];
    } else if ([self.optionButton.titleLabel.text isEqualToString:@"视频"]) {
        URL = [NSString stringWithFormat:KgetVideoByClick, KHostAddress, KOrganizationID, @(1), @"", @"", @(1)];
        URL = [URL stringByAppendingFormat:@"&keyWord=%@", self.searchBar.text];
    }
    
    UILabel *label = (UILabel *)[self.resultHeaderView viewWithTag:10];
    
    [ZRRequestManager POST:URL parameters:nil success:^(id responseObject) {
        DLog(@"%@", responseObject);
        if ([[responseObject objectForKey:@"error"] integerValue] == 0) {
            DLog(@"搜索成功");
            self.resultArr = [NSMutableArray arrayWithArray:responseObject[@"data"][@"items"]];
            [self.resultTableView reloadData];
            self.resultTableView.hidden = self.resultHeaderView.hidden = NO;
        } else {
            DLog(@"没有数据");
            self.resultArr = [NSMutableArray array];
            [self.resultTableView reloadData];
        }
        
        label.text = [NSString stringWithFormat:@"共%ld条记录", (unsigned long)self.resultArr.count];
        
    } failure:^(NSError *error) {
        DLog(@"%@", error);
    }];

}

@end
